<template>
    <el-card class="query-form">
        <el-form :inline="true" :model="form" label-width="120px" @submit.prevent="handleSubmit">
            <!-- 动态渲染查询字段 -->
            <el-row :gutter="20">
                <el-col v-for="(field, index) in fields" :key="index" :span="8"
                    :class="['form-item', { 'hidden-field': isHidden(index) }]">
                    <el-form-item :label="field.label" :prop="field.name">
                        <!-- 文本框 -->
                        <el-input v-if="field.type === 'text'" v-model="form[field.name]"
                            :placeholder="field.placeholder" />

                        <!-- 下拉框 -->
                        <el-select v-else-if="field.type === 'select'" v-model="form[field.name]"
                            :placeholder="field.placeholder" @change="handleSelectChange(field, index)">
                            <el-option v-for="option in field.options" :key="option.value" :label="option.label"
                                :value="option.value" />
                        </el-select>

                        <!-- 异步下拉框 -->
                        <el-select v-else-if="field.type === 'asyncSelect'" v-model="form[field.name]"
                            :placeholder="field.placeholder" :disabled="!isAsyncFieldReady(field)"
                            @visible-change="handleAsyncSelectOpen(field)">
                            <el-option v-for="option in field.asyncOptions" :key="option.value" :label="option.label"
                                :value="option.value" />
                        </el-select>

                        <!-- 日期选择器 -->
                        <el-date-picker v-else-if="field.type === 'date'" v-model="form[field.name]" type="datetime"
                            :placeholder="field.placeholder" format="YYYY-MM-DD HH:mm:ss"
                            value-format="YYYY-MM-DD HH:mm:ss" />
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 查询与重置按钮 -->
            <el-row>
                <el-col :span="24" class="form-actions">
                    <el-button type="primary" @click="handleSubmit">查询</el-button>
                    <el-button @click="handleReset">重置</el-button>
                </el-col>
            </el-row>
        </el-form>
    </el-card>
</template>

<script setup>
import { reactive, ref, watch, onMounted } from 'vue';

// 定义 props
const props = defineProps({
    fields: {
        type: Array,
        required: true,
        default: () => [],
    },
});

// 定义 emits
const emit = defineEmits(['search', 'reset']);

// 表单数据
const form = reactive({});

// 控制字段是否隐藏（用于展开/收起）
const isCollapse = ref(false);

// 控制异步下拉框的加载状态
const asyncLoading = ref({});

// 初始化表单数据
onMounted(() => {
    props.fields.forEach((field) => {
        form[field.name] = field.value || '';
        if (field.type === 'asyncSelect' && field.dependsOn) {
            // 初始化依赖字段的监听
            watch(
                () => form[field.dependsOn],
                async (newVal) => {
                    if (newVal) {
                        await loadAsyncOptions(field, newVal);
                    }
                },
                { immediate: true }
            );
        }
    });
});

// 处理下拉框变化（可能触发异步加载）
const handleSelectChange = (field, index) => {
    if (field.type === 'select' && field.nextDependsOn) {
        const nextField = props.fields[index + 1];
        if (nextField && nextField.type === 'asyncSelect') {
            nextField.asyncOptions = [];
            form[nextField.name] = '';
        }
    }
};

// 处理异步下拉框打开时的逻辑
const handleAsyncSelectOpen = async (field) => {
    if (field.asyncOptions.length === 0 && field.dependsOn) {
        const depValue = form[field.dependsOn];
        if (depValue) {
            await loadAsyncOptions(field, depValue);
        }
    }
};

// 加载异步下拉框的选项
const loadAsyncOptions = async (field, depValue) => {
    if (field.asyncLoad) {
        try {
            asyncLoading.value[field.name] = true;
            const options = await field.asyncLoad(depValue);
            field.asyncOptions = options;
        } catch (error) {
            console.error('加载异步选项失败:', error);
            field.asyncOptions = [];
        } finally {
            asyncLoading.value[field.name] = false;
        }
    }
};

// 判断异步下拉框是否就绪
const isAsyncFieldReady = (field) => {
    return !field.dependsOn || form[field.dependsOn];
};

// 判断字段是否隐藏（用于展开/收起）
const isHidden = (index) => {
    return isCollapse.value && index >= 4; // 示例：前4个字段显示，其余隐藏
};

// 提交表单
const handleSubmit = () => {
    emit('search', form);
};

// 重置表单
const handleReset = () => {
    props.fields.forEach((field) => {
        form[field.name] = field.value || '';
        if (field.type === 'asyncSelect') {
            field.asyncOptions = [];
        }
    });
    emit('reset');
};
</script>

<style scoped>
.query-form {
    padding: 20px;
}
.form-item {
    margin-bottom: 16px;
}
.hidden-field {
    display: none;
}
.form-actions {
    text-align: right;
}
</style>